package com.dayuanit.dy17.atm.atmbackoffice.service.impl;

import com.dayuanit.dy17.atm.atmbackoffice.dto.PowerDTO;
import com.dayuanit.dy17.atm.atmbackoffice.entity.Power;
import com.dayuanit.dy17.atm.atmbackoffice.mapper.PowerMapper;
import com.dayuanit.dy17.atm.atmbackoffice.service.IPowerService;
import com.dayuanit.dy17.atm.atmbackoffice.vo.PowerRequestVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Service
public class PowerServiceImpl implements IPowerService {

    @Autowired
    private PowerMapper powerMapper;

    @Override
    public void addPower(PowerRequestVO powerRequestVO) {
        Power power = new Power();

        power.setLevel(powerRequestVO.getLevel());
        power.setMenu(powerRequestVO.getMenu());
        power.setParentId(powerRequestVO.getParentId());
        power.setPowerKey(powerRequestVO.getPowerKey());
        power.setPowerValue(powerRequestVO.getPowerValue());
        power.setUrl(powerRequestVO.getUrl());
        powerMapper.insert(power);
    }

    @Override
    public List<Power> listPower(int level) {
        return powerMapper.listByLevel(level);
    }

    @Override
    public List<PowerDTO> listMenu() {
        List<Power> powers = powerMapper.listByMenu(1);
        List<PowerDTO> firstMenu = new ArrayList<>();

        for (Power power : powers) {
            if (power.getLevel() != 1) {
                continue;
            }

            PowerDTO powerDTO = new PowerDTO();
            firstMenu.add(powerDTO);

            powerDTO.setId(power.getId());
            powerDTO.setPowerValue(power.getPowerValue());
            powerDTO.setParentId(power.getParentId());
        }

        for (PowerDTO firstDTO : firstMenu) {
            List<PowerDTO> child = new ArrayList<>();
            firstDTO.setChild(child);

            for (Power power : powers) {
                if (power.getParentId().equals(firstDTO.getId())) {
                    PowerDTO secondMenu = new PowerDTO();
                    secondMenu.setPowerValue(power.getPowerValue());
                    secondMenu.setId(power.getId());
                    secondMenu.setParentId(power.getParentId());
                    child.add(secondMenu);
                }
            }
        }

        return firstMenu;
    }

    @Override
    public void addRolePower(long roleId, Set<Long> powerIds) {
        powerMapper.saveRoleRefPower(roleId, powerIds);
    }
}
